package com.cy.module;

import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.AccountMapRole;
import com.cy.model.AccountRole;
import com.google.common.collect.Lists;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/account")
public class AccountController extends WebApiController {

    @Override
    public void index() {
        Account account = getModel(Account.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<Account> accountPage = Account.dao.paginate(page, pageSize, "a.*,c.name AS companyName", account);
        renderBuiPage(accountPage, 200);
    }

    @Before(Tx.class)
    @Override
    public void update() {
        int id = getParaToInt();
        Account tempAccount = getModel(Account.class);
        Account account = Account.dao.findById(id);
        account.cover(tempAccount);

        Map<String, String []> paraMap = getParaMap();
        if(null != paraMap.get("newPassword") && null != paraMap.get("oldPassword")){
            String newPassword = paraMap.get("newPassword")[0];
            String oldPassword = paraMap.get("oldPassword")[0];
            if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(oldPassword)) {
                if (!account.matchPassword(oldPassword)) {
                    renderStatus(EnumConst.RetCode.USERNAME_OR_PASSWORD_ERROR.getCode(), "输入的旧密码不正确，请重新尝试。");
                    return;
                }
                account.setPassword(newPassword).entryptPassword();
            }
        }

        try{
            account.update();
            String roleIdStr = getPara("roleIds");
            String[] roleIdsArr = roleIdStr == null ? getParaMap().get("roleIds[]") : new String[]{roleIdStr};
            List<String> roleIds = roleIdsArr == null ? new ArrayList<String>(0) : Lists.newArrayList(roleIdsArr) ;
            List<AccountRole> originalRoles = account.getRoles();

            //排除相同元素不做修改
            for (Iterator<AccountRole> originalRolesIt = originalRoles.listIterator(); originalRolesIt.hasNext();){
                AccountRole originalRole = originalRolesIt.next();
                for(Iterator<String> roleIdsIt = roleIds.listIterator(); roleIdsIt.hasNext();){
                    Long rid = Long.valueOf(roleIdsIt.next());
                    if (originalRole.getId().equals(rid)){
                        originalRolesIt.remove();
                        roleIdsIt.remove();
                        break;
                    }
                }
            }

            List<String> originalRoleIds = new ArrayList<>(originalRoles.size());
            for (AccountRole ar : originalRoles)
                originalRoleIds.add(String.valueOf(ar.getId()));

            try {
                //删除原有多余的角色
                if (originalRoleIds.size() > 0)
                    AccountMapRole.dao.deleteAccountAndRole(new Object[]{account.getAccountId()}, originalRoleIds.toArray());
                //新增不存在的角色
                for (String rid : roleIds)
                    new AccountMapRole().setAccountRoleId(Long.valueOf(rid)).setAccountId(account.getAccountId()).save();
                renderSuccess();
            } catch (Exception e){
                e.printStackTrace();
                renderFail();
            }
            renderSuccess();
        } catch (Exception e){
            e.printStackTrace();
            renderFail();
        }
    }

    @Before(Tx.class)
    @Override
    public void save() {
        Account account = getModel(Account.class);
        try {
            account.save();
            String roleIdStr = getPara("roleIds");
            String[] roleIdsArr = roleIdStr == null ? getParaMap().get("roleIds[]") : new String[]{roleIdStr};
            if (roleIdsArr != null){
                List<String> roleIds = Lists.newArrayList(roleIdsArr) ;
                for (String roleId : roleIds)
                    new AccountMapRole().setAccountId(account.getAccountId()).setAccountRoleId(Long.valueOf(roleId)).save();
            }
            renderSuccess();
        } catch (Exception e){
            e.printStackTrace();
            renderFail();
        }
    }

    @Before(Tx.class)
    @Override
    public void delete() {
        try {
            String[] ids = getPara().split("-");
            Account.dao.deleteBatch("account_id", ids);
            AccountMapRole.dao.deleteBatch("account_id", ids);
            renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            renderFail();
        }
    }

    /**
     * 返回用户信息 用户公众号信息
     */
    public void getAccountInfo() throws IOException {
        JSONObject json = new JSONObject();
        int code = EnumConst.RetCode.SUCCESS.getCode();

        Account account = getLoginAccount();
        if (account != null) {
            account.remove("password", "salt");//删除数据（前端）
            json.put("data", account);
        }
        json.put("code", code);
        renderJson(json);

    }

    public void checkAccountUnique(){
        JSONObject json = new JSONObject();
        String account = getPara("account.account");
        boolean unique = Account.dao.checkAccountUnique(account);
        if (unique) {
            json.put("status", 0);
            json.put("msg", "该账号已存在！");
        }else{
            json.put("status", 1);
        }
        renderJson(json);
    }

    public void getRoles(){
        String accountId = getPara("accountId");
        List<AccountRole> accountRoles = null;
        if (StringUtils.isNotBlank(accountId)){
            Account account = Account.dao.findById(accountId);
            accountRoles = account.getRoles();
        }
        List<AccountRole> allRoles = AccountRole.dao.findAll();
        if (accountRoles != null){
            for (AccountRole r : allRoles){
                for (AccountRole role : accountRoles){
                    if (r.getId().equals(role.getId())){
                        r.put("checked", true);
                        break;
                    }
                }
            }
        }
        renderJson(allRoles);
    }

}